from random import sample

from django.shortcuts import render
from django.db.models import Q
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.status import *
from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination
from .serializers import LabelSerializer, TopicSerializer, TopicNoAnswerSerializer, LabelTopicSerializer
from utils.permissions import MyBasePermissions, auto_user

# Create your views here.
from work.models import Label, Topic


class LabelViewSet(ModelViewSet):
    queryset = Label.objects.all()
    serializer_class = LabelSerializer
    permission_classes = [IsAuthenticated, MyBasePermissions]

    @auto_user
    def create(self, request):  # 重写增加数据接口

        # 优化变成装饰器，写权限里
        # request.POST._mutable = True
        # 提交过来的数据用户id(字符串) = 需要修改为当前登录用户的id
        # request.data['user'] = str(request.user.id)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_201_CREATED)

    @auto_user
    def update(self, request, pk):  # 重写修改数据接口
        # 当前登录用户是不是标签的创造者
        if not Label.objects.filter(pk=pk, user=request.user):
            return Response({'msg': '您没有权限修改'})
        label = Label.objects.get(pk=pk, user=request.user)

        # 优化变成装饰器，写权限里
        # request.POST._mutable = True
        # 提交过来的数据用户id(字符串) = 需要修改为当前登录用户的id
        # request.data['user'] = str(request.user.id)
        serializer = self.get_serializer(label, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_200_OK)

    @action(methods=['get'], detail=True)
    def examination(self, request, pk):
        # 查询标签
        try:
            label = Label.objects.get(pk=pk)
        except Label.DoesNotExist:
            return Response(status=HTTP_404_NOT_FOUND)

        serializer = LabelTopicSerializer(label)
        return Response(serializer.data)


# 老师查看分页类
class TopicPaginationPagNumber(PageNumberPagination):
    page_size = 2  # 每页显示2条
    max_page_size = 1


class TopicViewSet(ModelViewSet):
    queryset = Topic.objects.filter(is_delete=False)
    serializer_class = TopicSerializer
    permission_classes = [IsAuthenticated, MyBasePermissions]
    pagination_class = TopicPaginationPagNumber

    @auto_user
    def create(self, request):  # 重写增加数据接口

        # 优化变成装饰器，写权限里
        # request.POST._mutable = True
        # 提交过来的数据用户id(字符串) = 需要修改为当前登录用户的id
        # request.data['user'] = str(request.user.id)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_201_CREATED)

    @auto_user
    def update(self, request, pk):  # 重写修改数据接口
        # 当前登录用户是不是标签的创造者
        if not Label.objects.filter(pk=pk, user=request.user):
            return Response({'msg': '您没有权限修改'})
        label = Label.objects.get(pk=pk, user=request.user)

        # 优化变成装饰器，写权限里
        # request.POST._mutable = True
        # 提交过来的数据用户id(字符串) = 需要修改为当前登录用户的id
        # request.data['user'] = str(request.user.id)
        serializer = self.get_serializer(label, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=HTTP_200_OK)


# 学生刷题分页类
class TopicPagination(LimitOffsetPagination):
    default_limit = 2  # 默认每页2条数据
    max_limit = 10  # 每页最大条数


class TopicStudentViewSet(GenericViewSet, ListModelMixin):
    queryset = Topic.objects.exclude(Q(label__name__contains='考试') | Q(is_delete=True))
    serializer_class = TopicNoAnswerSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = TopicPagination

    @action(methods=['get'], detail=False)
    def random(self, request):  # 随机抽题功能（模拟考）
        # 指定数量
        data = dict(request.query_params)
        size = int(data.get('size')[0]) if data.get('size') else 3  # 如果有参数就按参数的来分页，否则就每页3条

        # TopicNoAnswerSerializer(Topic.objects.exclude(Q(label__name__contains='考试') | Q(is_delete=True)))
        serializer = self.get_serializer(self.get_queryset(), many=True)

        # sample()，从指定序列中随机抽取指定数量的数据
        return Response(sample(serializer.data, size))